package com.milk.milkmedia.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PersistableBundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioGroup;

import com.milk.milkmedia.R;
import com.milk.milkmedia.api.BaseActivity;
import com.milk.milkmedia.api.ConstantField;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by 微安 on 2015/11/12.
 */
public class GuideActivity extends Activity implements View.OnClickListener,ViewPager.OnPageChangeListener{

    private ViewPager mViewPager;
    private PopupWindow mPopupWindow;
    private LinearLayout mIndicatorLayout;
    private List<ImageView> mIndicatorList;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_guide);
        initView();
        initVersion();
        clearFirstSP();
        initViewPager();
    }

    private void initViewPager() {
        List<View> viewList = new ArrayList<>();
        List<Integer> imageList = new ArrayList<>();
        imageList.add(R.drawable.ic_frame_guide_1);
        imageList.add(R.drawable.ic_frame_guide_1);
        for (int i = 0; i < imageList.size(); i++) {
            View v4 = getLayoutInflater().inflate(R.layout.item_popu_guide,
                    null);
            ImageView imageView = (ImageView) v4.findViewById(R.id.item_popu_img);
            imageView.setImageResource(imageList.get(i));
            if (i == imageList.size() - 1) {
                Button start = (Button) v4.findViewById(R.id.start);
                start.setVisibility(View.VISIBLE);
                start.setOnClickListener(this);
            }
            viewList.add(v4);
        }
        mViewPager.setAdapter(new MyPagerAdapter(viewList));
        mViewPager.setOnPageChangeListener(this);

        // 加入小圆点
        for (int i = 0; i < viewList.size(); i++) {
            ImageView indicator = new ImageView(this);
            if (i == 0) {
                indicator
                        .setImageResource(R.drawable.ic_frame_page_indicator_focused);
            } else {
                indicator.setImageResource(R.drawable.ic_frame_page_indicator);
            }
            indicator.setLayoutParams(new ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            mIndicatorLayout.addView(indicator);
            mIndicatorList.add(indicator);
        }

        // 启动欢迎界面
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 检查该Context是否获得焦点（使用mPopupWindow崩溃）
                while (!GuideActivity.this.hasWindowFocus()) {
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                // 启动mPopupWindow的动画效果
                handler.sendEmptyMessage(0);
            }
        }).start();

    }
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 这里必须用handler来延迟启动不然会报异常
            // android.view.WindowManager$BadTokenException: Unable to add
            // window -- token null is not valid; is your activity running?
            mPopupWindow.setAnimationStyle(R.style.GuideAnim);
            mPopupWindow.showAtLocation(GuideActivity.this.findViewById(R.id.img_guide),
                    Gravity.CENTER, 0, 0);
        }
    };
    private void clearFirstSP() {
        SharedPreferences sp = getSharedPreferences(ConstantField.SP_FIRST_USE,
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear().apply();
    }
    private class MyPagerAdapter extends PagerAdapter {
        private List<View> viewList;

        public MyPagerAdapter(List<View> viewList) {
            this.viewList = viewList;
        }

        @Override
        public int getCount() {
            return viewList.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(View arg0, int arg1, Object arg2) {
            ((ViewPager) arg0).removeView(viewList.get(arg1));
        }

        @Override
        public Object instantiateItem(View arg0, int arg1) {
            ((ViewPager) arg0).addView(viewList.get(arg1));
            return viewList.get(arg1);
        }

    }
    private void initVersion() {
        String version = null;
        try {
            version = getApplication().getPackageManager().getPackageInfo(
                    getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e1) {
            e1.printStackTrace();
        }
        SharedPreferences sp = getSharedPreferences(ConstantField.SP_CONFIG,
                Context.MODE_PRIVATE);
        sp.edit().putString(ConstantField.SP_VERSION, version).apply();
    }

    private void initView() {
        View popupView = getLayoutInflater().inflate(
                R.layout.popu_guide, null);
        mViewPager = (ViewPager) popupView.findViewById(R.id.popu_viewpage);
        mIndicatorLayout = (LinearLayout) popupView
                .findViewById(R.id.indicator_layout);
        mPopupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT,
                RadioGroup.LayoutParams.MATCH_PARENT, true);
        mIndicatorList = new ArrayList<>();
    }



    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.start:
                Intent intent;
                intent = new Intent(this, RegisterActivity.class);
                startActivity(intent);
                finish();
                break;
            default:
                break;
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        for (int i = 0; i < mIndicatorList.size(); i++) {
            mIndicatorList.get(i).setImageResource(
                    R.drawable.ic_frame_page_indicator);
        }
        mIndicatorList.get(position).setImageResource(
                R.drawable.ic_frame_page_indicator_focused);
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }
//屏蔽返回键
    @Override
    public void onBackPressed() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mPopupWindow!=null){
            mPopupWindow.dismiss();
        }
    }
}
